﻿using Microsoft.AspNetCore.Mvc;
using Digitalmes.Application;
using Digitalmes.Scada.Models;

namespace Digitalmes.Scada.WebApi;

/// <summary>
/// 设备状态 API
/// </summary>
[ApiExplorerSettings(GroupName = "scada")]
public sealed class ScadaDeviceApi : IDynamicWebApiService, ITransientDependency
{
    private readonly IDeviceFactory _deviceFactory;

    public ScadaDeviceApi(IDeviceFactory deviceFactory)
    {
        _deviceFactory = deviceFactory;
    }

    /// <summary>
    /// 获取指定通道下指定分组中所有的标记集合。
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    [HttpGet]
    public List<TagModel>? GetTags(ScadaDeviceParam param)
    {
        var channel = _deviceFactory.GetChannels().FirstOrDefault(s => s.Name == param.ChannelName);
        var tags = channel?.Devices.SelectMany(s => s.TagGroups).FirstOrDefault(s => s.Name == param.TagGroupName)?.Tags;
        return tags?.Select(s => From(s)).ToList() ?? new(0);
    }

    private static TagModel From(Tag tag)
    {
        var tag1 = FromTag(tag);
        tag1.Children = new List<TagModel>(tag.NormalTags.Select(FromTag));
        return tag1;

        static TagModel FromTag(Tag tag)
        {
            TagModel model = new()
            {
                TagId = tag.TagId,
                Name = tag.Name,
                Address = tag.Address,
                Length = tag.Length,
                DataType = tag.DataType,
                Flag = tag.Flag,
                Keynote = tag.Keynote,
                DisplayName = tag.DisplayName,
                Description = tag.Description,
                ScanRate = tag.ScanRate,
                PublishMode = tag.PublishMode,
                CurveUsage = tag.CurveUsage,
                ClientAccess = tag.ClientAccess,
                Identity = tag.Identity,
                Group = tag.Group,
                ValueUsage = tag.ValueUsage,
                IsArray = tag.IsArray(),
            };
            return model;
        }
    }
}
